<template>
  <ex-dialog
    width="1000px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    @closeDialog="handleClose"
  >	
		<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
      <el-form-item label="勋章名称：" prop="equityCardId" >
        <el-select v-model="ruleForm.equityCardId" placeholder="全部" size="small" :disabled="disable" filterable>
          <el-option v-for="item in cardList" :key="item.id" :label="item.cardName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="行业：" prop="industryId">
        <el-select v-model="ruleForm.industryId" placeholder="全部" size="small" :disabled="disable" filterable>
          <el-option v-for="item in industryList" :key="item.id" :label="item.industryName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序：" prop="sort" >
        <el-input type="number" v-model.number="ruleForm.sort" placeholder="请填写排序" style="width: 200px" ></el-input>
      </el-form-item>
      <div class="lable_l">
        <div class="left">等级称号</div>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <template>
        <div class="imgBox" v-for="(item,index) in ruleForm.medalLevelList" :key="index">
          <div class="delBtn" v-if="index != 0">
            <el-button type="danger" size="mini" @click="handleDelete(index)">删除</el-button>
          </div>
          <el-row >
            <el-col :span="8">
              <el-form-item :label="`称号名称${index+1}：`"  label-width="110px" :prop="'medalLevelList.' + index + '.name'" :rules="rules.name">
                <el-input v-model="item.name" placeholder="请填写称号名称" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="消费激励值："  label-width="110px" :prop="'medalLevelList.' + index + '.stimulate'" :rules="rules.stimulate">
                <el-input v-model="item.stimulate" placeholder="请填写消费激励值" maxlength="50" oninput="value=value.match(/^\d+(?:\.\d{0,2})?/)">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="8">
              <el-form-item label="叠加封顶值：" label-width="110px" :prop="'medalLevelList.' + index + '.capping'" :rules="rules.capping">
                <el-input v-model="item.capping" placeholder="请填写叠加封顶值" maxlength="50" oninput="value=value.match(/^\d+(?:\.\d{0,2})?/)">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row >
            <el-col :span="8">
              <el-form-item label="升级贡献：" label-width="110px" :prop="'medalLevelList.' + index + '.contribution'" :rules="rules.contribution">
                <el-input v-model="item.contribution" placeholder="请填写升级贡献" maxlength="50">
                  <template slot="append">点</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="升级规则：" label-width="110px" :prop="'medalLevelList.' + index + '.rule'" :rules="rules.rule">
                <el-input v-model="item.rule" placeholder="请填写升级规则" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="8">
              <el-form-item label="激活等级图片：" :prop="'medalLevelList.' + index + '.activateImg'" :rules="rules.activateImg" ref="imgRef">
                <ImageUploadMore :limit="1" :fileSize="20" @successImg="(e) => {getactivateImg(e,index)}" :value="item.activateImg">
                </ImageUploadMore>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="未激活等级图片：" :prop="'medalLevelList.' + index + '.notActivateImg'" :rules="rules.notActivateImg" ref="imgRef">
                <ImageUploadMore :limit="1" :fileSize="20" @successImg="(e) => {getnotActivateImg(e,index)}" :value="item.notActivateImg">
                </ImageUploadMore>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </template>
      
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">确认</el-button>
				<el-button @click="handleClose('ruleForm')">取消</el-button>
			</el-form-item>
		</el-form>
  </ex-dialog>
</template>
<script>
// components
import Loading from '@/components/Loading/index'
// api
import {
  addMedal, 
  editMedal,
  industryList,
  cardList,
  medalInfo,
} from '@/api/equityManager/medalConfig'
import { disable } from '../../../../api/merchants'

export default {
  components: {
    Loading
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    var validateContribution= (rule, value, callback) => { 
      var reg = /(^[1-9]\d*$)/
      if (value === '') {
        callback(new Error('请填写升级贡献'));
      } else if (!reg.test(value)) {
        callback(new Error('请填写大于0的整数'));
      }  else {
        callback();
      }
    };
    var validateCapping= (rule, value, callback) => {
      var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/
      if (value === '') {
        callback(new Error('请填写叠加封顶值'));
      } else if (!reg.test(value)) {
        callback(new Error('请填写大于0的数字'));
      }  else {
        callback();
      }
    };
    var validateStimulate= (rule, value, callback) => {
      var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/
      if (value === '') {
        callback(new Error('请填写消费激励值'));
      } else if (!reg.test(value)) {
        callback(new Error('请填写大于0的数字'));
      }  else {
        callback();
      }
    };
    return {
      loading: false,
      industryList: [],//行业类型
      cardList: [],//勋章类型
      roleList: [],
      disable: false,
      title: '新增勋章玩法',
      imgLoading: false,
      sort: '',
			ruleForm: {
        equityCardId: '',//数字权益卡id
        id: '',//勋章id
        industryId: '',//行业id
        medalLevelList: [
          {
            activateImg: '',//激活等级图片
            capping: '',//	叠加封顶值（单位:%）
            contribution: '',//升级贡献点
            name: '',//	等级称号
            notActivateImg: '',//	未激活等级图片
            rule: '',//升级规则
            stimulate: '',//消费激励值（单位:%）
          },
        ],
        
			},
			rules: {
          equityCardId: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          industryId: [
            { required: true,message: '请选择', trigger: 'change' }
          ],
          sort:  [
            { required: true,message: '请填写排序',trigger: 'blur' }
          ],
          name: [
            { required: true,message: '请填写等级称号',trigger: 'blur' }
          ],
          activateImg: [
            { required: true,message: '请上传激活等级图片', trigger: 'change' }
          ],
          capping: [
            { required: true,validator: validateCapping,trigger: 'blur' }
          ],
          contribution: [
            { required: true,validator: validateContribution,trigger: 'blur' }
          ],
          notActivateImg: [
            { required: true,message: '请上传未激活等级图片', trigger: 'change' }
          ],
          rule: [
            { required: true,message: '请填写升级规则',trigger: 'blur' }
          ],
          stimulate: [
            { required: true,validator: validateStimulate, trigger: 'blur' }
          ],
        }
    }
  },
  computed: {
   
  },
  created() {
    
    
    console.log('this.id',this.id)
    if(this.pathType == 'add'){
      this.title = '新增勋章玩法'
      this.ruleForm.id = ''
      this.getindustry()
      this.getCardList()
    }else{
      this.ruleForm.id = this.id
      this.disable = true
      this.getDatail()
      this.title = '编辑勋章玩法'
      this.getindustry()
      this.getCardList()
    }
	},
  methods: {
    inputnum(){
      this.input = this.input.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')
    },
    //获取行业
    getindustry(){
      var data = {
        id: this.ruleForm.id
      }
      industryList(data).then(res => {
        this.industryList = res.result
      })
    },
    //获取勋章
    getCardList(){
      var data = {
        id: this.ruleForm.id
      }
       cardList(data).then(res => {
        this.cardList = res.result
      })
    },
    //获取详情
    getDatail(){
      var id = this.id
      medalInfo(id).then(res => {
        this.ruleForm = res.result
      })
    },
    /** logo */
    getImg(e) {
      this.ruleForm.img = e
      this.$refs['imgRef'].clearValidate();
    },
    getactivateImg(e,index){
      console.log('index',index)
      this.ruleForm.medalLevelList[index].activateImg = e
    },
    getnotActivateImg(e,index){
      this.ruleForm.medalLevelList[index].notActivateImg = e
      
    },
    //新增等级称号
    handleAdd(){
      var obj = {
        activateImg: '',
        capping: '',
        contribution: '',
        name: '',
        notActivateImg: '',
        rule: '',
        stimulate: '',
      }
      this.ruleForm.medalLevelList.push(obj)
    },
    //删除等级称号
    handleDelete(ind){
      this.ruleForm.medalLevelList.splice(ind,1)
    },
    //新建勋章玩法
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          if(this.pathType == 'add'){
            var data = {
            ...this.ruleForm
            }
            addMedal(data).then(res => {
             
              setTimeout(() => {
                this.handleClose()
                this.$message.success('创建成功')
                this.$emit('success')
                this.loading = false
              }, 1000);
            }).catch(()=> {
              this.loading = false
            }).finally(() => {
              
            })
          }else if(this.pathType == 'edit'){
            var data = {
            ...this.ruleForm
            }
            editMedal(data).then(res => {
              
              setTimeout(() => {
                this.$message.success('修改成功')
                this.handleClose()
                this.$emit('success')
                this.loading = false
              }, 1000);
            }).catch(()=> {
              this.loading = false
            }).finally(() => {

            })
          }
            
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    
		//取消
    handleClose(formName) {
      this.$emit('update:visible', false)
			// this.$refs[formName].resetFields();
    },
		//确认
		handleConfirm(){
			this.$emit('success', '你好')
		},
    handleSuccess(msg) {
      if (msg === '已拒绝') {
        var type = 'error'
      } else {
        var type = 'success'
      }
      this.$message({
        message: msg,
        type: type,
        duration: 1500,
        onClose: () => {
          this.handleClose()
          this.$emit('success')
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
		padding: 0 !important;
  }
	::v-deep .ex--dialog--main {
    padding: 10px 20px !important; 
  }
}
::v-deep .avatar-uploader2 .el-upload {
  width: 100% !important;
}

.avatar-uploader2 {
  width: 130px;
  height: 130px;
  text-align: center;
  line-height: 130px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
}

.banner_img {
  width: 130px;
  height: 130px;
}
.el-input{

}
.lable_l{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 0 20px 80px ;
  .left{
    margin-right: 20px;
  }
}
.imgBox{
  border: 1px solid #f5f5f5;
  border-radius: 12px;
  padding: 10px;
  margin-bottom: 16px;

  .name{
    font-size: 16px;
    color: #606266;
    margin-bottom: 10px;
    padding-left: 50px;
  }
}
.delBtn{
  display: flex;
  justify-content: flex-end;
  padding-bottom: 20px;
}
</style>